package com.yyk.yiliao.ui.home.activity;

import android.os.Bundle;
import androidx.viewpager.widget.ViewPager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseActivity;
import com.yyk.yiliao.adapter.GvAdapter;
import com.yyk.yiliao.adapter.VpAdapter;
import com.yyk.yiliao.base.BaseRecyclerAdapter;
import com.yyk.yiliao.base.BaseRecyclerHolder;
import com.yyk.yiliao.bean.Grid_Info;
import com.yyk.yiliao.bean.Pharmacy_Info;
import com.yyk.yiliao.ui.activity.detail.activity.Detail_Activity;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.widget.diver.more.SpacesItemDecoration;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.util.rx.RxUtils;
import com.yyk.yiliao.bean.ShopBrand_Info;
import com.yyk.yiliao.bean.StoreCustomclass_Info;
import com.yyk.yiliao.bean.StoreNear_Info;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 在线药房
 */
public class Pharmacy_Activity extends BaseActivity {

    @BindView(R.id.mPharmacy_rv)
    RecyclerView mPharmacyRv;
    @BindView(R.id.mPharmacy_zjyf) //最近药房
            LinearLayout mPharmacyZjyf;
    @BindView(R.id.vp)
    ViewPager vp;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.b_picture)
    ImageView bPicture;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.rb_star)
    RatingBar rbStar;
    @BindView(R.id.tv_star)
    TextView tvStar;
    @BindView(R.id.tv_distant)
    TextView tvDistant;
    @BindView(R.id.img_type)
    ImageView imgType;
    @BindView(R.id.img_invoice)
    ImageView imgInvoice;
    @BindView(R.id.img_isself)
    ImageView imgIsself;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.ll_search)
    LinearLayout llSearch;

    //假数组数据
    private BaseRecyclerAdapter<Pharmacy_Info> adapter;
    private int[] img = {R.mipmap.img_sp_1, R.mipmap.img_sp_2, R.mipmap.img_sp_3, R.mipmap.img_sp_4, R.mipmap.img_sp_5, R.mipmap.img_sp_6, R.mipmap.img_sp_7, R.mipmap.img_sp_8, R.mipmap.img_sp_9, R.mipmap.img_sp_10, R.mipmap.img_sp_11, R.mipmap.img_sp_12, R.mipmap.img_sp_13, R.mipmap.img_sp_14, R.mipmap.img_sp_15, R.mipmap.img_sp_16, R.mipmap.img_sp_17, R.mipmap.img_sp_18,};
    private String[] miaoshu = {"云南白药喷雾剂气雾剂...", "珍视明四味珍层冰硼滴...", "达喜铝碳酸镁片20片", "白云山板蓝根颗粒10g*30", "千金药业妇科千金片", "善存多维元素(29)100片", "斯利安叶酸片"
            , "九芝堂驴胶补血颗粒30袋", "迪巧维D钙咀嚼片120片", "21金维他多维元素100片", "曹清华牌薏辛除湿止痛...", "奇正消痛贴膏风湿肩周...", "国华天麻首乌片200片", "喜辽复修护凝胶20g",
            "感康复方氨酚烷胺片12片", "云南白药牙膏 留兰香型...", "同仁堂乌鸡白凤丸", "九芝堂六味地黄丸浓缩丸"};
    private String[] price = {"¥39", "¥36", "¥25", "¥23", "¥69", "¥129", "¥77", "¥326", "¥98", "¥169", "¥498", "¥69", "¥135", "¥144", "¥29", "¥18", "¥93", "¥18"};

    private List<Pharmacy_Info> pharmacyList;
    private List<View> viewList;
    private List<Grid_Info> infoList;
    //20
    private String proName[] = {"附近药店", "男科用药", "妇科用药", " 养生花茶", "儿科用药", "个人护理", "皮肤用药", "成人用品", "医疗器械", "传统滋补"};
    private int proImg[] = {R.mipmap.icon_fjyf, R.mipmap.icon_nankeyy, R.mipmap.icon_fukeyy, R.mipmap.icon_yshc, R.mipmap.icon_ekyy, R.mipmap.icon_grhl, R.mipmap.icon_pfyy, R.mipmap.icon_cryp, R.mipmap.icon_ylqx, R.mipmap.icon_ctzb};
    private int mPagerSize = 10;
    private int totalPage; //多少页
    private ImageView[] ivPoints;//圆点
    private int currentPage;//当前页数
    private List<StoreNear_Info.DataBean> data;

    @Override
    public int getLayoutId() {
        return R.layout.activity_pharmacy;
    }

    @Override
    public void initView() {
        initToolbar();


    }

    private void initToolbar() {
        setTitle("在线药房");
        setBackArrow();
    }

    @Override
    public void initData() {
        mPharmacyRv.setFocusable(false);
        initPost();
    }

    private void initPost() {
        //        setTopTitleVp();
        setIcon();
        setRexiaoShop();
        setZuijinYaoFang();
    }

    /**
     * 最近药房
     */
    private void setZuijinYaoFang() {
        //        map.put("lon", String.valueOf(116.40311));
//        map.put("lat", String.valueOf(39.917548));
        String jingdu = Hawk.get("经度");
        String weidu = Hawk.get("纬度");
        Map<String, String> map = new TreeMap<>();
        map.put("dis", 500000 + "");
        map.put("lat", String.valueOf(weidu));
        map.put("lon", String.valueOf(jingdu));
        map.put("page", "1");

        map.put("sign", Md5Util2.createSign(map));
        RxUtils instance = RxUtils.getInstance();
        instance.retrofit.create(ApiService.class).postStornear(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<StoreNear_Info>() {

                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(StoreNear_Info info) {
                        Logger.i("附近药店:" + info.toString());
                        if (info.getCode() == 1) {
                            mPharmacyZjyf.setVisibility(View.VISIBLE);
                            data = info.getData();
                            StoreNear_Info.DataBean dataBean = data.get(0);
                            tvName.setText(dataBean.getName());
                            tvAddress.setText(dataBean.getAddress());
                            float star = dataBean.getStar();
                            rbStar.setRating(star / 2);
                            tvStar.setText(star + "");
                            int isself = dataBean.getIsself();
                            if (isself == 1) {
                                imgIsself.setVisibility(View.VISIBLE);
                            } else {
                                imgIsself.setVisibility(View.GONE);
                            }
                            int invoice = dataBean.getInvoice();
                            if (invoice == 1) {
                                imgInvoice.setVisibility(View.VISIBLE);
                            } else {
                                imgInvoice.setVisibility(View.GONE);
                            }
                            int type = dataBean.getType();
                            if (type == 1) {
                                imgType.setVisibility(View.VISIBLE);
                            } else {
                                imgType.setVisibility(View.GONE);
                            }
                            tvDistant.setText(dataBean.getDistant() + "km");
                            Glide.with(mActivity).load(ApiService.BASE_URL + dataBean.getPic()).into(bPicture);
                        }else{
                            mPharmacyZjyf.setVisibility(View.GONE);
                        }
                    }
                });


    }

    /**
     * 热销商品
     */
    private void setRexiaoShop() {
        Map<String, String> map = new TreeMap<>();
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postShopBrand(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<ShopBrand_Info>() {

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();


                    }

                    @Override
                    public void onNext(ShopBrand_Info info) {
                        if (info.getCode() == 1) {
                            final List<ShopBrand_Info.DataBean> data = ((ShopBrand_Info) info).getData();
                            BaseRecyclerAdapter<ShopBrand_Info.DataBean> adapter = new BaseRecyclerAdapter<ShopBrand_Info.DataBean>(Pharmacy_Activity.this, data, R.layout.adapter_item_pharmacy) {
                                @Override
                                public void convert(BaseRecyclerHolder holder, ShopBrand_Info.DataBean item, int position, boolean isScrolling) {
                                    holder.setText(R.id.b_hospital_name, item.getName());
                                    holder.setText(R.id.b_money, "¥ " + item.getMoney());
                                    holder.setText(R.id.b_drname, item.getDrname());
                                    //设置图片
                                    holder.setImageByUrl(R.id.b_picture, ApiService.BASE_URL + item.getPic());
                                }
                            };

                            mPharmacyRv.setLayoutManager(new GridLayoutManager(Pharmacy_Activity.this, 3, GridLayoutManager.VERTICAL, false));

                            // TODO 很牛逼的分割线
                            mPharmacyRv.addItemDecoration(new SpacesItemDecoration(12, 20));
                            mPharmacyRv.setAdapter(adapter);
                            adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(RecyclerView parent, View view, int position) {
                                    //把药品ID传过去  商品详情
//
//                                    EventBus.getDefault().postSticky(new MessageEvent(data.get(position).getId() + ""));
//                                    startAct(Detail_Activity.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putInt("id", data.get(position).getId());
                                    startAct(Detail_Activity.class, bundle);

                                }
                            });
                        }

                    }
                });
    }

    /**
     * 设置可以滑动的VpGv
     */
//    private void setTopTitleVp() {
//        infoList = new ArrayList<>();
//        for (int i = 0; i < proName.length; i++) {
//            Grid_Info info = new Grid_Info(proImg[i], proName[i]);
//            infoList.add(info);
//        }
//        totalPage = (int) Math.ceil(infoList.size() * 1.0 / mPagerSize);
//        LayoutInflater inflater = LayoutInflater.from(this);
//        viewList = new ArrayList<>();
//        for (int i = 0; i < totalPage; i++) {
//            GridView gridView = (GridView) inflater.inflate(R.layout.gridview_layout, vp, false);
//            gridView.setAdapter(new GvAdapter(infoList, Pharmacy_Activity.this, i, mPagerSize));
//            viewList.add(gridView);
//        }
//        vp.setAdapter(new VpAdapter(viewList));
//        ivPoints = new ImageView[totalPage];
//        for (int i = 0; i < ivPoints.length; i++) {
//            ImageView imgView = new ImageView(this);
//            imgView.setLayoutParams(new ViewGroup.LayoutParams(10, 10));
//            if (i == 0) {
//                imgView.setImageResource(R.mipmap.icon_ftmann);
//            } else {
//                imgView.setImageResource(R.mipmap.icon_tmdhan);
//            }
//            ivPoints[i] = imgView;
//            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//            lp.leftMargin = 10;
//            lp.rightMargin = 10;
//            ll.addView(imgView, lp);
//        }
//
//
//        vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
//            @Override
//            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//
//            }
//
//            @Override
//            public void onPageSelected(int position) {
//                setImagePointSelect(position);
//                currentPage = position;
//            }
//
//            @Override
//            public void onPageScrollStateChanged(int state) {
//
//            }
//        });
//
//
//    }

    /**
     * 切换小圆点
     *
     * @param selectItems
     */
    public void setImagePointSelect(int selectItems) {
        for (int i = 0; i < ivPoints.length; i++) {
            if (i == selectItems) {
                ivPoints[i].setImageResource(R.mipmap.icon_ftmann);
            } else {
                ivPoints[i].setImageResource(R.mipmap.icon_tmdhan);
            }
        }
    }

    @OnClick({R.id.mPharmacy_zjyf, R.id.ll_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.mPharmacy_zjyf:
                if (data != null) {
                    mPharmacyZjyf.setVisibility(View.VISIBLE);

                    StoreNear_Info.DataBean dataBean = data.get(0);
                    int id = dataBean.getId();
                    String name = dataBean.getName();
                    String pic = dataBean.getPic();
                    String address = dataBean.getAddress();
                    int star = dataBean.getStar();
                    int isself = dataBean.getIsself();
                    int invoice = dataBean.getInvoice();
                    int type = dataBean.getType();
                    String distant = dataBean.getDistant();

                    Bundle bundle = new Bundle();
                    bundle.putString("bean", (id + "," + name + "," + pic + "," + address + "," + star + "," + isself + "," + invoice + "," + type + "," + distant));
                    startAct(PharmacyList_Activity.class, bundle);
                }else{
                    mPharmacyZjyf.setVisibility(View.GONE);
                }
                break;
            case R.id.ll_search:
//                Intent intent = new Intent(mActivity, PharmacySearch_Activity.class);
//                int location[] = new int[2];
//                llSearch.getLocationOnScreen(location);
//                intent.putExtra("x", location[0]);
//                intent.putExtra("y", location[1]);
//                startActivity(intent);
//                overridePendingTransition(0, 0);
                break;
        }
    }

    public void setIcon() {
        Map<String, String> map = new TreeMap<>();
//        map.put("cid", 0 + "");
        map.put("type", 1 + "");

        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postStoreCustomclass(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<StoreCustomclass_Info>() {

                    @Override
                    public void onCompleted() {
                        //完成的时候调用

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();


                    }

                    @Override
                    public void onNext(StoreCustomclass_Info info) {
                        if (info.getCode() == 1) {
                            List<StoreCustomclass_Info.DataBean> data = info.getData();
                            infoList = new ArrayList<>();
                            infoList.add(new Grid_Info(000000000, null + "", "附近药店"));
                            for (int i = 0; i < data.size(); i++) {
                                Grid_Info grid_info = new Grid_Info(data.get(i).getId(), data.get(i).getIcon(), data.get(i).getName());
                                infoList.add(grid_info);
                            }
                            totalPage = (int) Math.ceil(infoList.size() * 1.0 / mPagerSize);
                            Logger.e(totalPage + "totalPage");
                            LayoutInflater inflater = LayoutInflater.from(Pharmacy_Activity.this);
                            viewList = new ArrayList<>();
                            for (int i = 0; i < totalPage; i++) {
                                GridView gridView = (GridView) inflater.inflate(R.layout.gridview_layout, vp, false);
                                gridView.setAdapter(new GvAdapter(infoList, Pharmacy_Activity.this, i, mPagerSize));
                                viewList.add(gridView);
                            }
                            vp.setAdapter(new VpAdapter(viewList));
                            ivPoints = new ImageView[totalPage];
                            for (int i = 0; i < ivPoints.length; i++) {
                                ImageView imgView = new ImageView(Pharmacy_Activity.this);
                                imgView.setLayoutParams(new ViewGroup.LayoutParams(10, 10));
                                if (i == 0) {
                                    imgView.setImageResource(R.mipmap.icon_ftmann);
                                } else {
                                    imgView.setImageResource(R.mipmap.icon_tmdhan);
                                }
                                ivPoints[i] = imgView;
                                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                                lp.leftMargin = 10;
                                lp.rightMargin = 10;
                                ll.addView(imgView, lp);
                            }
                            vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                                @Override
                                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                                }

                                @Override
                                public void onPageSelected(int position) {
                                    setImagePointSelect(position);
                                    currentPage = position;
                                }

                                @Override
                                public void onPageScrollStateChanged(int state) {

                                }
                            });
                        } else {

                        }

                    }
                });
    }

}
